//
//  NSConditionDemo.m
//  JKThreadTest
//
//  Created by 王冲 on 2018/10/25.
//  Copyright © 2018年 JK科技有限公司. All rights reserved.
//

#import "NSConditionDemo.h"

@interface NSConditionDemo ()

@property(nonatomic,strong) NSCondition *conditLock;

@property(nonatomic,strong) NSMutableArray *data;



@end

@implementation NSConditionDemo

-(instancetype)init{
    
    if (self = [super init]) {
        
        self.conditLock = [[NSCondition alloc]init];
        
    }
    
    return self;
}

- (void)otherTest
{
    [[[NSThread alloc] initWithTarget:self selector:@selector(__remove) object:nil] start];
    
    [[[NSThread alloc] initWithTarget:self selector:@selector(__add) object:nil] start];
}

// 生产者-消费者模式

// 线程1
// 删除数组中的元素
- (void)__remove
{
    [self.conditLock lock];
    NSLog(@"__remove - begin");
    
    if (self.data.count == 0) {
        // 等待(等待的条件和唤醒的条件 cond 必须保持一致)
        [self.conditLock wait];
    }
    
    [self.data removeLastObject];
    NSLog(@"删除了元素");
    
    [self.conditLock unlock];
}

// 线程2
// 往数组中添加元素
- (void)__add
{
    [self.conditLock lock];
    
    sleep(1);
    
    [self.data addObject:@"Test"];
    NSLog(@"添加了元素");
    
    // 信号 (等待的条件和唤醒的条件 cond 必须保持一致)
    // pthread_cond_signal(&_cond);
    [self.conditLock signal];
    // 广播 (唤醒所有等待的条件 cond 必须保持一致)
    // pthread_cond_broadcast(&_cond);
    //[self.conditLock broadcast];
    
    [self.conditLock unlock];
}

@end
